package org.video.mine.fragment;

import androidx.databinding.DataBindingUtil;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.tabs.TabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.video.mine.HomeDocModel;
import org.video.mine.R;
import org.video.mine.Urls;
import org.video.mine.adapter.HomeTabTitleAdapter;
import org.video.mine.databinding.HomeFragmentBinding;
import org.video.mine.entity.HomeTitleEntity;
import org.video.mine.event.ChangePage;
import org.video.mine.event.LoadFailedEvent;
import org.video.mine.fragment.home.Dongman2;
import org.video.mine.fragment.home.FifthFragment;
import org.video.mine.fragment.home.FirstFragment;
import org.video.mine.fragment.home.ForthFragment;
import org.video.mine.fragment.home.SecondFragment;
import org.video.mine.fragment.home.ThirdFragment;
import org.video.mine.model.ClickModel;
import org.video.mine.utils.ScreenUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private HomeFragmentBinding homeBinding;
    private List<HomeTitleEntity> titleEntities = new ArrayList<>();
    private List<Fragment> fragments;
    private HomeTabTitleAdapter tabTitleAdapter;
    private ViewModelStoreOwner owner;
    String[] titles = new String[]{"首页","电影","电视剧","动漫"/*,"综艺"*/};
    String[] hrefs = new String[]{Urls.homeUrl0,Urls.dianying,Urls.dianshi,Urls.donghua,Urls.qiTa};
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    if (titleEntities!=null){
                        if (titleEntities.size()>=titles.length){
                            fragments.add(FirstFragment.newInstance());
                            fragments.add(SecondFragment.newInstance());
                            fragments.add(ThirdFragment.newInstance());
                            fragments.add(Dongman2.newInstance());
//                            fragments.add(FifthFragment.newInstance());
                        }
                    }
                    tabTitleAdapter = new HomeTabTitleAdapter(getChildFragmentManager(),titleEntities,getContext(),fragments);
                    homeBinding.viewPager.setOffscreenPageLimit(2);
                    homeBinding.viewPager.setAdapter(tabTitleAdapter);
                    homeBinding.viewPager.setCurrentItem(0);

                    homeBinding.tableTitle.setupWithViewPager(homeBinding.viewPager);
                    homeBinding.tableTitle.setTabTextColors(Color.GRAY,Color.RED);
                    reflex(homeBinding.tableTitle);
                    break;
            }
        }
    };
    private HomeDocModel homeDocModel;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        homeBinding = DataBindingUtil.inflate(inflater,R.layout.home_fragment,container,false);
        return homeBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);
       owner = this;
       homeDocModel = new ViewModelProvider(this).get(HomeDocModel.class);
       homeBinding.setClick(new ClickModel());
       EventBus.getDefault().register(this);
       initView();
    }

    private void initData() {
        fragments = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                /*titleEntities.addAll(JsoupGet.getHomeTitle(owner,Urls.homeUrl));*/
                for (int i=0;i<titles.length;i++){
                    titleEntities.add(new HomeTitleEntity(titles[i],hrefs[i]));
                }
                mHandler.sendEmptyMessage(0);
            }
        }).start();
    }

    private void reflex(final TabLayout tableTitle) {
        tableTitle.post(new Runnable() {
            @Override
            public void run() {
                LinearLayout mTableStrip = (LinearLayout) tableTitle.getChildAt(0);
                int dp10 = ScreenUtils.dp2px(5);
                int stripCount = mTableStrip.getChildCount();
                for (int i=0; i<stripCount; i++){
                    try {
                        View tabView = mTableStrip.getChildAt(i);
                        Field mTextViewField = tabView.getClass().getDeclaredField("textView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        tabView.setPadding(0,0,0,0);
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width==0){
                            mTextView.measure(0,0);
                            width = mTextView.getMeasuredWidth();
                        }
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.weight = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void initView() {
        initData();
    }

    @Subscribe
    public void changePage(ChangePage changePage){
        if (changePage!=null){
            homeBinding.viewPager.setCurrentItem(changePage.page);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
